﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ListIt.DAL;

namespace Dispatcher.Views
{
    public partial class FrmDispatchToTaxi : Form
    {
        private BacklogPresenter _backlogPresenter;
        JobBackLogModelView _jobView;
        ListItDAL _DAL;
        List<Taxi> _taxiList;

        public FrmDispatchToTaxi(BacklogPresenter backlogPresenter, JobBackLogModelView jobView) : base()
        {
            InitializeComponent();
            _backlogPresenter = backlogPresenter;
            _jobView = jobView;
            _DAL = _backlogPresenter.DAL;
        }

        private void FrmDispatcDihToTaxi_Load(object sender, EventArgs e)
        {
            lbJobId.Text = _jobView.ID.ToString();
            lbCustomer.Text = _jobView.Customer;
            lbMobile.Text = _jobView.Mobile;
            lbPickup.Text = _jobView.Pickup;

            var collection = from taxis in _DAL.ListItEntities.Taxis
                             where (taxis.Available == true) && (taxis.JobPending == -1)
                             orderby taxis.LicenseNo
                             select taxis;

            _taxiList = collection.ToList();

            foreach (Taxi taxi in _taxiList)
            {
                cmbTaxiLicenseNo.Items.Add(taxi.LicenseNo);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (cmbTaxiLicenseNo.Text == "")
            {
                MessageBox.Show("Please select a Taxi from the list", "Select a Taxi", MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show(string.Format("Are you sure you want to dispatch this job to taxi {0}?",
              cmbTaxiLicenseNo.Text), "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
              System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            JobBackLog job = _DAL.ListItEntities.JobBackLogs.SingleOrDefault(a => a.ID == _jobView.ID);

            // check if the job still exists
            if (job == null)
            {
                MessageBox.Show("While processing your request, another taxi driver has already taken the job.",
                    "Job taken", MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }

            job.DriverAssignmentMarker = DateTime.Now;
            _backlogPresenter.DispatchJob(job, _taxiList.Find(a => a.LicenseNo == cmbTaxiLicenseNo.Text));

            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}
